<template>
  <page-view v-loading="loading">
    <!--  二维码图片所在的父视图  -->
    <div
        v-for="(item, index) in tableData"
        class="qrcode-content"
        :id="getTitleAndQrCodeIdByIndex(index)"
        v-show="showBk"
        ref="print"
    >
      <div
          :key="index"
          :id="getQrCodeIdByIndex(index)"
          class="qrcode-bk"
      >
        <div class="qrcode-pic" ref="codeItem"></div>
        <div class="qrcode-title">二维码描述</div>
      </div>
    </div>

    <vue-qr id="logoQrCode" :logoSrc="imageUrl" text="https://www.baidu.com" :size="120"></vue-qr>

    <div class="footer">
      <el-button @click="creatQrCode" plain>生成</el-button>
      <el-button @click="saveImg" plain>保存</el-button>
      <el-button @click="handlePrint" plain>打印</el-button>
    </div>

    <el-table
        :data="tableData"
        border
    >
      <el-table-column label="序号" width="100" type="index" align="center" />
      <el-table-column
          prop="name"
          label="转账来自"
          align="center"
      >
        <template v-slot="scope">
          <div class="link-type" @click="nameClicked">{{scope.row.name}}</div>
        </template>
      </el-table-column>
    </el-table>

    <div class="qrcode-pic">
      <img :src="base64Image" alt="">
    </div>

    <el-dialog
        fullscreen
        v-model="innerVisible"
        title="二维码打印"
        center
        append-to-body
        destroy-on-close
    >
      <div id="print" ref="print">
        <div v-for="(item, index) in allImages2" class="qrcode-bk">
          <!--    临时生成      -->
<!--          <vue-qr :logoSrc="imageUrl" :text="item.text" :size="120" :margin="0"></vue-qr>-->
          <!--    直接显示      -->
          <img :src="item" :key="index" alt="" width="120" height="140" />
        </div>
      </div>
      <template #footer>
        <!--        <el-button v-if="!hideFooter" type="primary" v-print="'#print'">开始打印</el-button>-->
        <el-button v-if="!hideFooter" type="primary" @click="handlePrint">开始打印</el-button>
      </template>
    </el-dialog>
  </page-view>
</template>

<script>
import QRCode from "qrcodejs2";
import html2canvas from 'html2canvas';
import vueQr from 'vue-qr/src/packages/vue-qr.vue'
import likeIcon2 from '@/assets/like_s.png'
import print from 'vue3-print-nb';
import printJS from 'print-js';

import axios from 'axios';
import FormData from 'form-data';

export default {
  name: "WorkdemoDetail",
  components: {
    vueQr,
  },
  data() {
    return {
      tableData:[],
      loading:false,

      // 当需要生成二维码的时候 显示canvas承接标签
      showBk:false,

      // imageUrl: 'https://img0.baidu.com/it/u=3049998987,1866756846&fm=253&fmt=auto&app=138&f=JPEG?w=501&h=500',
      imageUrl:require('../../assets/like_s.png'),
      innerVisible:false,
      // 纯二维码图片
      allImages:[],
      // canvas生成的带标题和二维码的图片
      allImages2:[],
      // canvas生成的带标题和二维码的图片blob
      allBlobs:[],
      // 存放canvas生成的图片base64
      allResults:[],
      hideFooter:false,

      base64Image:'',
    }
  },
  created() {
    let arr = [];
    for (let i = 0; i < 5; i += 1) {
      let text = `https://blog.csdn.net/weixin_42601136?name=${i}`
      const obj = {
        text,
        name:'张三',
      }
      arr.push(obj);
    }
    this.tableData = arr;
  },
  mounted() {
    // this.creatQrCode();
    // console.log('vueQr:',vueQr)
    console.log('baseTag：', this.baseTag);

    console.log('query:', this.$route.query);
  },
  activated() {
    console.log('组件被激活：', this.$route.query);
  },
  methods:{
    creatQrCode() {
      this.loading = true;
      this.showBk = true;
      this.$nextTick(()=> {
        const arr = this.tableData;
        arr.forEach((item, index)=>{
          this.$refs.codeItem[index].innerHTML = "";
          let qrcode = new QRCode(this.$refs.codeItem[index], {
            // 二维码内容
            text: item.text,
            width: 100,
            height: 100,
            render: 'table',
            colorDark: "#333333", //二维码颜色
            colorLight: "#ffffff", //二维码背景色
            correctLevel : QRCode.CorrectLevel.H
          })

          // 二维码生成以后再删除
          let childs = document.getElementsByClassName('qrcode-pic')[index].childNodes;
          document.getElementsByClassName('qrcode-pic')[index].removeChild(childs[0]);
        });
      })

      setTimeout(() => {
        this.saveImg();
      }, 1500)
    },

    /**
     * 将标题和二维码图片放到一起的标签id
     * @param index
     * @returns {string}
     */
    getTitleAndQrCodeIdByIndex(index) {
      return `titleQrCode-${index}`;
    },

    /**
     * 获取生成的二维码图片
     * @param index
     * @returns {string}
     */
    getQrCodeIdByIndex(index) {
      return `myQrCode${index}`;
    },

    /**
     * 保存二维码图片
     */
    saveImg() {
      const arr = this.tableData;
      let images = [];
      let needDownload = false;
      for (let i = 0; i < arr.length; i += 1) {
        let idName = this.getQrCodeIdByIndex(i);
        // 生成二维码之后其实是个img 所以获取完id之后还要获取到这个img 才能下载成功
        let canvasData = this.$refs.codeItem[i].getElementsByTagName('img')
        console.log('canvasData:', canvasData[0])
        let img = canvasData[0].src;
        console.log('img:', img)

        // let imageDiv = document.createElement('img');
        // imageDiv.src = canvasData[0].src;
        // imageDiv.onload = (res) => {
        //   console.log('res:', res)
        // }

        // let myBlob = this.base64ToBlob(imageDiv.getAttribute('src'));
        // console.log('myBlob:', myBlob)

        // let img = ''
        images.push(img);

        if (needDownload) {
          let a = document.createElement("a");
          a.href = img;
          a.download = `二维码${i}.png`;
          a.click();
        }
      }

      // 弹窗显示
      this.allImages = images;
      console.log('images:', images);
      this.innerVisible = false;

      // 直接下载中间带图片的二维码
      if (needDownload) {
        let logoDiv = document.getElementById('logoQrCode')
        let a = document.createElement("a");
        a.href = logoDiv.src;
        a.download = `logo.png`;
        a.click();
        a.remove();
      }

      // 等页面先刷新完毕 - 直接批量打印了
      this.$nextTick(() => {
       setTimeout(() => {
         // 下载底部带文字的所有二维码
         this.downloadResult();
       }, 1000)
      })
    },

    base64ToBlob(dataurl) {
      var arr = dataurl.split(','),
          mime = arr[0].match(/:(.*?);/)[1],
          bstr = atob(arr[1]),
          n = bstr.length,
          u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new Blob([u8arr], { type: mime });
    },

    /**
     * 通过二维码图片以及下面的文本 使用canvas截取生成新的图片
     */
    downloadResult() {
      let needDownload = false;
      let imagesNew = [];
      let imagesBlob = [];
      for (let i = 0; i < this.tableData.length; i += 1) {
        // 获取便签内的内容
        let targetId = this.getTitleAndQrCodeIdByIndex(i);
        let canvasID = document.getElementById(targetId);
        let a = document.createElement('a');
        html2canvas(canvasID).then(canvas => {
          // 画布绘制
          let dom = document.body.appendChild(canvas);
          dom.style.display = 'none';
          a.style.display = 'none';
          document.body.removeChild(dom);

          // 图片blob
          let blob = this.dataURLToBlob(dom.toDataURL('image/png'));
          // 根据blob转化为可以下载的链接 - 输出一个包含Blob数据的url
          let url = URL.createObjectURL(blob);
          console.log('当前索引生成的带文字图片链接：', url);
          imagesNew.push(url);
          imagesBlob.push(blob);

          this.convertImageToBase64(blob, i);

          if (needDownload) {
            let name = `二维码+标题${index}`;
            a.setAttribute('href', url);
            // 图片名称
            a.setAttribute('download', name + '.png')
            document.body.appendChild(a);
            a.click();
            URL.revokeObjectURL(blob);
            document.body.removeChild(a);
          }
        });
      }

      setTimeout(() => {
        console.log("canvas生成的所有新图数组", imagesNew);
        this.allImages2 = imagesNew;
        this.allBlobs = imagesBlob;
        this.innerVisible = false;
        console.log('this.allResults:', this.allResults);
        this.showBk = false;
        this.loading = false;
      }, 3000)
    },

    /**
     *
     * @param dataUrl
     * @returns {*}
     */
    dataURLToBlob(dataUrl) {
      let arr = dataUrl.split(','), mime = arr[0].match(/:(.*?);/)[1],
          bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new Blob([u8arr], { type: mime })
    },


    /**
     * 打印二维码
     */
    handlePrint() {
      this.hideFooter = true;
      this.$nextTick(()=> {
        // 打印时 先让弹窗底部按钮隐藏
        window.print()
      })


      // 这是你要上传的图片链接 测试图片上传接口
      const blob = this.allBlobs[0];
      this.convertImageToBase64(blob);

      const formData = new FormData();
      formData.append('image', {
        uri: this.allImages2[0],
        type: 'image/jpeg',
        name: 'image.jpg',
      });

      axios.post('http://example.com/upload', formData).then(response => {
        console.log(response);
      }).catch(error => {
        console.error(error);
      });
    },

    /**
     * 将图片链接转化为base64字符
     */
    convertImageToBase64(blob, index) {
      const reader = new FileReader();
      let arr = this.allResults;
      reader.onload = (e) => {
        const base64Image = e.target.result;
        this.base64Image = base64Image;
        let isIn = arr.some(item => item == base64Image);
        if (!isIn) {
          arr.push(base64Image);
        }
        this.allResults = arr;
        if (arr.length == this.tableData.length) {
          this.showBk = false;
        }

        // 图片生产完毕 移除该div
        let divId = this.getTitleAndQrCodeIdByIndex(index);
        let canvasBkDiv = document.getElementById(divId);
        canvasBkDiv.style.display = 'none';
      };
      reader.readAsDataURL(blob);
    },

    print() {
      printJS({
        // 需要打印的元素的ID
        printable: 'print',
        type: 'html',
        targetStyles:[
          'display: inline-block;',
          'text-align: center;',
          'margin:10px 10px;',
        ],
        documentTitle: '打印内容'
      });
    }
  }
}
</script>

<style scoped>

.content {

}

.qrcode-bk {
  display: inline-block;
  text-align: center;
  margin:10px 10px;
}

/*每个承载二维码图片和标题的父标签 用以做画布截取范围*/
.qrcode-content {
  width:120px;
}

.qrcode-pic {
  width:100px;
  height:100px;
  background-color: #fff;
  padding: 6px;
  box-sizing: border-box;
}

/*二维码标题*/
.qrcode-title {
  font-size: 14px;
  width: 100px;
  margin-top: 10px;
}

.footer {
  margin-top: 20px;
}

.dialog-footer {
  display: block;
}
</style>
